﻿using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;

namespace Model
{
    public class GenericContext : InventizerEntities
    {
        public string UserName { get; set; }

        object GetPrimaryKeyValue(DbEntityEntry entry)
        {
            var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
            return objectStateEntry.EntityKey.EntityKeyValues[0].Value;
        }

        public override int SaveChanges()
        {
            var modifiedEntities = ChangeTracker.Entries()
                .Where(p => p.State == EntityState.Modified).ToList();
            var now = DateTime.UtcNow;

            foreach (var change in modifiedEntities)
            {
                var entityName = change.Entity.GetType().Name;
                var primaryKey = GetPrimaryKeyValue(change);

                foreach (var prop in change.CurrentValues.PropertyNames)
                {
                    var property = change.Property(prop);
                    if (change.GetDatabaseValues().GetValue<object>(prop) == null) break;
                    var originalValue = change.GetDatabaseValues().GetValue<object>(prop).ToString();                    
                    var currentValue = property.CurrentValue.ToString();
                    if (UserName == null)
                        UserName = String.Empty;
                    if (originalValue != currentValue)
                    {
                        AUDIT log = new AUDIT()
                        {
                            ENTITYNAME = entityName,
                            PRIMARYKEYVALUE = primaryKey.ToString(),
                            PROPERTYNAME = prop,
                            OLDVALUE = originalValue,
                            NEWVALUE = currentValue,
                            DATETIME = now,
                            USERNAME = UserName,
                            OPERATION = "UPDATE"
                        };
                        AUDIT.Add(log);
                    }
                }
            }
            return base.SaveChanges();
        }
    }
}
